<?php
namespace App\Job;

use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;

use App\Query\ShopQuery;
use App\Query\UserPayQuery;
use App\Repository\ShopRepository;
use App\Repository\UserRepository;
use App\Repository\LevelRepository;

// 店铺考核
class ShopCheckJob
{
    /**
     * @AsyncQueueMessage
     */
    public function push()
    {
        // 获取需要考核的店铺
        $check = ShopQuery::statusOk(ShopQuery::check())->get();

        // 循环
        foreach($check as $shop)
        {
            // 分红
            [$repository, $is] = $this->red($shop);
            
            // 店铺考核
            $repository->checkTime();
            
            // 上级如果业绩够，将享受一次分红
            if($repository->shop && $is)
            {
                $this->red($repository->shop, true);
            }
        }
    }
    
    // 判断业绩并分红, type 为上级
    public function red($shop, $type = false)
    {
        $shop = ShopRepository::make($shop);
        $user = UserRepository::make($shop->user);
        $level = LevelRepository::make($shop->user->level);
        
        // 获取店铺业绩
        $money = UserPayQuery::totalMoney($shop->getCheckTime(), $shop->model()->userPay());

        // 判断等级考核需要的业绩
        if($is = $level->shopMoney($money))
        {
            // 算出分红
            $money = $type ? $level->shopShopPrize($money) : $level->shopPrize($money);

            // 加入奖
            $user->moneyFullAdd($money, '店铺业绩考核分红', 'shop_prize');
        }
        
        return [$shop, $is];
    }
}